package com.basic.business;

import java.io.*;
import java.nio.channels.ClosedByInterruptException;
import java.util.Arrays;
import java.util.Timer;
import java.util.TimerTask;

public class FileTransferDemo {

    // 文件传输线程（与方案一相同）
    static class FileTransferTask extends Thread {
        private final InputStream in;
        private final OutputStream out;

        public FileTransferTask(InputStream in, OutputStream out) {
            this.in = in;
            this.out = out;
        }

        @Override
        public void run() {
            try (InputStream in = this.in; OutputStream out = this.out) {
                byte[] buffer = new byte[8192];
                int bytesRead;
                long totalBytes = 0;

                System.out.println("文件传输开始...");

                while (!Thread.currentThread().isInterrupted()
                        && (bytesRead = in.read(buffer)) != -1) {
                    out.write(buffer, 0, bytesRead);
                    totalBytes += bytesRead;

                    // 模拟大文件传输时的延迟（实际使用时删除）
                    Thread.sleep(100); // 100ms延迟方便观察取消效果
                }

                System.out.println("文件传输完成，共传输 " + totalBytes + " bytes");
            } catch (ClosedByInterruptException e) {
                System.out.println("传输被中断（ClosedByInterruptException）");
            } catch (IOException | InterruptedException e) {
                if (isInterrupted()) {
                    System.out.println("传输被中断（InterruptedException）");
                } else {
                    e.printStackTrace();
                }
            } finally {
                System.out.println("执行资源清理...");
            }
        }

        // 传输控制器（增强版）
        static class TransferController {
            private FileTransferTask transferThread;
            private volatile boolean isRunning;

            public void startTransfer(String source, String target) {
                try {
                    InputStream in = new FileInputStream(source);
                    OutputStream out = new FileOutputStream(target);

                    transferThread = new FileTransferTask(in, out);
                    isRunning = true;
                    transferThread.start();
                } catch (IOException e) {
                    e.printStackTrace();
                    isRunning = false;
                }
            }

            public void cancelTransfer() {
                if (transferThread != null && transferThread.isAlive()) {
                    System.out.println("\n正在取消传输...");

                    // 发送中断信号
                    transferThread.interrupt();
                    isRunning = false;

                    // 关闭流强制中断阻塞IO
                    try {
                        if (transferThread.in != null) transferThread.in.close();
                    } catch (IOException e) {
                        System.out.println("输入流关闭异常: " + e.getMessage());
                    }
                    try {
                        if (transferThread.out != null) transferThread.out.close();
                    } catch (IOException e) {
                        System.out.println("输出流关闭异常: " + e.getMessage());
                    }
                }
            }

            public boolean isRunning() {
                return isRunning;
            }
        }

        /****************** 测试方法 ******************/
        public static void main(String[] args) throws InterruptedException {
            // 1. 准备测试文件
            String sourceFile = "test_source.bin";
            String targetFile = "test_target.bin";

            // 生成一个100MB的测试文件（可根据需要调整大小）
            createTestFile(sourceFile, 100 * 1024 * 1024); // 100MB
            System.out.println("测试文件已生成: " + sourceFile);

            // 2. 创建传输控制器
            TransferController controller = new TransferController();

            // 3. 启动传输
            System.out.println("启动文件传输...");
            controller.startTransfer(sourceFile, targetFile);

            // 4. 启动定时取消任务（5秒后取消）
            new Timer().schedule(new TimerTask() {
                @Override
                public void run() {
                    if (controller.isRunning()) {
                        controller.cancelTransfer();
                    }
                }
            }, 5000);

            // 5. 监控进度（每秒显示状态）
            while (controller.isRunning()) {
                Thread.sleep(1000);
                System.out.print(".");
            }

            // 6. 验证结果
            System.out.println("\n最终状态: " +
                    (new File(targetFile).exists() ? "文件已部分传输" : "传输未完成"));
        }

        // 生成测试文件的工具方法
        private static void createTestFile(String filename, int sizeBytes) {
            try (OutputStream out = new FileOutputStream(filename)) {
                byte[] buffer = new byte[1024];
                Arrays.fill(buffer, (byte) 0xFF); // 填充数据

                int bytesRemaining = sizeBytes;
                while (bytesRemaining > 0) {
                    int writeSize = Math.min(buffer.length, bytesRemaining);
                    out.write(buffer, 0, writeSize);
                    bytesRemaining -= writeSize;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}